import { loginApi, getUserInfoApi, getBaseUserInfoApi } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: {}
  // this.$store.state.user.userInfo.username
}

const getters = {}

const mutations = {
  setToken(state, newToken) {
    setToken(newToken)
    state.token = newToken
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  // 清除token,清除用户信息
  logout(state) {
    state.token = ''
    removeToken()
    state.userInfo = {}
    // 退出的时候清空路由对象中的路由规则
    resetRouter()
  }
}

const actions = {
  // 调登录接口
  login(store, loginForm) {
    return new Promise((resolve, reject) => {
      loginApi(loginForm).then(res => {
        const token = res.data
        store.commit('setToken', token)
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  async getUserInfo(store) {
    const res = await getUserInfoApi()
    // console.log(res)
    const res2 = await getBaseUserInfoApi(res.data.userId)
    // res2.data.staffPhoto = 'http://www.baidu.com/xxxx'
    const baseData = { ...res.data, ...res2.data }
    store.commit('setUserInfo', baseData)
    // return 的目的 是为了8天之后做权限使用
    return baseData
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
